import axios from "axios"
import {getToken} from "@/utils/storage.js";

//全局定义一个单例的axios对象
const request = axios.create({
  baseURL: "",
  timeout: 600000
});
//全局拦截器，所有请求都会先执行这个
request.interceptors.request.use(config => {
    //设置为ajon请求
    config.headers['Content-Type'] = 'application/json;charset=utf-8'
  // Do something before request is sent
  const token = getToken();
  if(token !== null){
      //在请求的头部加入token
      config.headers["token"] = token;
  }
  return config;
  },error => {
  // Do something with request error
  return Promise.reject(error);
  });

//response拦截器
//可以在调用接口响应后，统一的处理返回结果
request.interceptors.response.use(
    response => {
      let res = response
      //如果返回的是文件,就返回
      if (response.config.responseType === 'blob') {
        return res
      }
      //如果是string, 就转成json对象
      if (typeof res === 'string') {
        //如果res 不为null, 就进行转换成json对象
        res = res ? JSON.parse(res) : res
      }
      return res;
    },
    error => {
      console.log("err", error)
      return Promise.reject(error);
    }
)
// 导出axios对象
export default request;
